<?php
	//创建websocket服务器对象，监听0.0.0.0:9502端口
	$ws = new swoole_websocket_server("0.0.0.0", 9999);

	//监听WebSocket连接打开事件
	$ws->on('open', function ($ws, $request) {
//	    var_dump($ws);
//	    var_dump($request);
	});

    function __autoload($class_name) {
        require_once 'controller/' . $class_name . '.php';
    }

	//监听WebSocket消息事件
	$ws->on('message', function ($ws, $frame) {
	    $curData = json_decode($frame->data, true);
	    $className = ucfirst(explode('/', $curData['url'])[1]);
	    $funcName = explode('/', $curData['url'])[2];

	    try{
            $controllerRes = (new $className())->$funcName($curData['data']);
            $res = [
                'code' => 0,
                'result' => $controllerRes
            ];
        }catch (\Exception $e){
	        $res = [
	            'code' => 1,
                'message' => '系统发生错误：'.$e->getMessage()
            ];
        }

        if (!isset($res['url'])){
            $res['url'] = $curData['url'];
        }

	    $ws->push($frame->fd, json_encode($res));
	});

	//监听WebSocket连接关闭事件
	$ws->on('close', function ($ws, $fd) {
	    echo "client-{$fd} is closed\n";
	});

	$ws->start();

